// 打包处理
import { cpSync, existsSync, readdir, rmSync, stat, unlink, writeFileSync } from 'fs';
import { join } from 'path';
import { execSync } from 'child_process';

const mode = process.argv[2].replace('--mode=', '');

if (mode === 'prod') {
  // 递归创建文件夹
  // mkdirSync('./dist', { recursive: true });

  //   递归复制文件
  cpSync('./config', './dist/config', { recursive: true });

  // npm镜像加速
  cpSync('./.npmrc', './dist/.npmrc');
  // 浏览器
  cpSync('./.cache', './dist/.cache', {
    recursive: true
  });
  cpSync('./.puppeteerrc.cjs', './dist/.puppeteerrc.cjs', {
    recursive: true
  });

  //   删除文件
  if (existsSync('./dist/config/config.yaml')) {
    rmSync('./dist/config/config.yaml');
  }
  if (existsSync('./dist/config/command.json')) {
    rmSync('./dist/config/command.json');
  }
  //   创建package.json 把没用的配置移除
  const { dependencies } = require('./package.json');
  writeFileSync(
    './dist/package.json',
    JSON.stringify(
      {
        scripts: {
          dev: 'node ./src/app.js',
          start: 'pm2 startOrRestart ./pm2.json',
          stop: 'pm2 stop k-bot',
          delete: 'pm2 delete k-bot',
          list: 'pm2 list',
          save: 'pm2 save --force',
          log: 'pm2 logs --lines 200 k-bot'
        },
        dependencies,
        devDependencies: {
          pm2: '^5.2.2'
        }
      },
      null,
      2
    )
  );
  let pm2 = {
    apps: [
      {
        cwd: './',
        watch: ['src/**/*.js', 'example/**/*.js', 'plugins/**/*.js'],
        ignore_watch: ['node_modules', './config/command.json'],
        watch_delay: 1000,
        min_uptime: 10000,
        max_restarts: 3,
        watch_options: {
          followSymlinks: false
        },
        name: 'k-bot',
        script: './src/app.js',
        error_file: './pm2/error.log',
        out_file: './pm2/out.log',
        log_date_format: 'YYYY-MM-DD HH:mm Z',
        max_memory_restart: '512M',
        cron_restart: '0 8 * * *' //设置每天八点重启 (根据系统时间判断)
      }
    ]
  };
  writeFileSync('./dist/pm2.json', JSON.stringify(pm2, null, 2));
}

if (mode === 'pkg') {
  //   递归复制文件

  cpSync('./config', './dist/config', { recursive: true });
  // npm镜像加速
  cpSync('./.npmrc', './dist/.npmrc');

  cpSync('./dist/example', './dist/dist/example', { recursive: true });
  cpSync('./config', './dist/dist/config', { recursive: true });
  cpSync('./dist/plugins', './dist/dist/plugins', {
    recursive: true
  });
  cpSync('./dist/src', './dist/dist/src', {
    recursive: true
  });
  // 浏览器
  cpSync('./.cache', './dist/.cache', {
    recursive: true
  });
  cpSync('./.puppeteerrc.cjs', './dist/.puppeteerrc.cjs', {
    recursive: true
  });

  cpSync('./.cache', './dist/dist/.cache', {
    recursive: true
  });

  //   删除文件
  if (existsSync('./dist/dist/config/config.yaml')) {
    rmSync('./dist/dist/config/config.yaml');
  }
  if (existsSync('./dist/dist/config/config_default.yaml')) {
    rmSync('./dist/dist/config/config_default.yaml');
  }

  if (existsSync('./dist/dist/config/command.json')) {
    rmSync('./dist/dist/config/command.json');
  }

  //   创建package.json 把没用的配置移除
  const { dependencies, name, pkg } = require('./package.json');
  const pac = {
    name,
    bin: './src/app.js',
    scripts: {
      'build': 'set PKG_CACHE_PATH=../.pkg-cache/&& pkg . --compress GZip',
      'build-l': 'export PKG_CACHE_PATH=../.pkg-cache/&& pkg . --compress GZip',
      'postinstall': 'patch-package'
    },
    pkg,
    dependencies,
    devDependencies: {
      'pkg': '5.8.1',
      'patch-package': '^7.0.0'
    }
  };

  writeFileSync('./dist/package.json', JSON.stringify(pac, null, 2));
  cpSync('./patches', './dist/patches', { recursive: true });
  let ml = '';
  if (process.platform === 'win32') {
    ml = 'npm run build';
  } else if (process.platform === 'linux') {
    ml = 'npm run build-l';
  } else {
    ml = 'npm run build';
  }
  console.log('开始npm i');
  execSync('cd ./dist && npm i', {
    stdio: 'inherit'
  });

  cpSync('./dist/node_modules', './dist/dist/node_modules', { recursive: true });

  console.log('开始打包');
  execSync(`cd ./dist && ${ml}`, {
    stdio: 'inherit'
  });

  cpSync('./dist/dist', './dist_pkg', { recursive: true });
  rmSync('./dist', {
    recursive: true
  });
  console.log('完成');
}

if (mode === 'compile') {
  cpSync('./plugins', './dist/plugins', {
    recursive: true
  });
  nots('./dist/plugins');
}
// 删除ts
function nots(dir: string) {
  readdir(dir, function (err, files) {
    files.forEach(function (filename) {
      var src = join(dir, filename);
      stat(src, function (err, st) {
        if (err) {
          throw err;
        }
        // 判断是否为文件
        if (st.isFile()) {
          if (/\.ts$/.test(filename)) {
            unlink(src, err => {
              if (err) throw err;
              console.log('成功删除：' + src);
            });
          }
        } else {
          // 递归作为文件夹处理
          nots(src);
        }
      });
    });
  });
}
